'use client'

import React, { useState, useRef, useEffect } from 'react';

interface VideoPlayerProps {
  src: string;
  className?: string;
  objectFit?: 'contain' | 'cover' | 'fill';
  autoPlay?: boolean;
  defaultAspectRatio?: string; // 视频加载前的默认长宽比
}

export default function VideoPlayer({ 
  src, 
  className, 
  objectFit, 
  autoPlay = true, 
  defaultAspectRatio = "16/9" // 视频加载前的默认长宽比
}: VideoPlayerProps) {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [aspectRatio, setAspectRatio] = useState(defaultAspectRatio);
  const [isMuted, setIsMuted] = useState(true); // 初始静音状态
  const [isPlaying, setIsPlaying] = useState(false);

  useEffect(() => {
    const video = videoRef.current;
    if (!video) return;

    const handleLoadedMetadata = () => {
      // 获取视频的实际长宽比
      const videoAspectRatio = video.videoWidth / video.videoHeight;
      setAspectRatio(`${videoAspectRatio}`);
    };

    const handlePlay = () => setIsPlaying(true);
    const handlePause = () => setIsPlaying(false);

    video.addEventListener('loadedmetadata', handleLoadedMetadata);
    video.addEventListener('play', handlePlay);
    video.addEventListener('pause', handlePause);

    return () => {
      video.removeEventListener('loadedmetadata', handleLoadedMetadata);
      video.removeEventListener('play', handlePlay);
      video.removeEventListener('pause', handlePause);
    };
  }, [src]);

  // 处理视频点击，启用声音并播放
  const handleVideoClick = (e: React.MouseEvent) => {
    e.preventDefault();
    const video = videoRef.current;
    if (!video) return;
    
    // 总是确保取消静音
    if (isMuted) {
      video.muted = false;
      setIsMuted(false);
    }
    
    // 切换播放状态
    if (video.paused) {
      video.play().catch(console.error);
    } else {
      video.pause();
    }
  };
  return (
    <div 
      className={`${className} relative`}
      style={{ 
        aspectRatio: aspectRatio,
        backgroundColor: '#000', // 加载时显示黑色背景
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
      }}
    >
      <video
        ref={videoRef}
        className='w-full h-full'
        style={{ objectFit: objectFit || 'cover' }}
        controls
        loop
        playsInline
        preload="metadata"
        autoPlay={autoPlay}
        muted={isMuted}
      >
        <source src={src} type="video/mp4" />
        您的浏览器不支援影片播放。
      </video>
      
      {/* 只在暂停且静音时显示播放按钮覆盖层 */}
      {!isPlaying && isMuted && (
        <div 
          className="absolute inset-0 flex items-center justify-center cursor-pointer"
          onClick={handleVideoClick}
        /> 
      )}
    </div>
  );
}